﻿// Apache-2.0 License
// Copyright (c) 2021-2022 朱飞龙
// 电话/微信：18706708563  QQ群：136192142

using Admin.NET.Application.Util.Extension;
using Radius.NET.Interface.Kingdee.Entity;

namespace Radius.NET.Interface.Kingdee.Service.BasicInfoModule;


/// <summary>
/// 配方档案服务
/// </summary>
[ApiDescriptionSettings(KingdeeConfigConst.GroupName, Order = 002)]
public class ProductBomService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<ProductBOM> producBomRespository;

    private readonly KingdeeUtil _kingdeeUtil;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="_producBomRespository"></param>
    /// <param name="kingdeeUtil"></param>
    public ProductBomService(SqlSugarRepository<ProductBOM> _producBomRespository,
        KingdeeUtil kingdeeUtil)
    {
        producBomRespository = _producBomRespository;
        _kingdeeUtil=kingdeeUtil;
    }

    #region 同步金蝶云星空物料清单到本地
    /// <summary>
    /// 同步金蝶云星空物料清单到本地
    /// </summary>
    /// <returns></returns>
    [HttpPost("/kindeeIcloud/basicinfo/bomlist/{cid}"), AllowAnonymous]
    public async Task<object> SyncBomList(int cid, string BDate)
    {
        var KingdeeUtil = await _kingdeeUtil.GetClient("kindeeIcloud_basicinfo_bomlist");
        List<ProductBOM> bomList = new();
        if (string.IsNullOrEmpty(BDate))
            BDate = DateTime.Now.ToString("yyyy-MM-dd");

        //获取云星空BOM清单
        var list = KingdeeUtil.Query<ENG_BOM_Dto>(KingdeeFormConst.ENG_BOM, $"FUseOrgId.FNumber = '{KingdeeConfigConst.ORGID}' and FCreateDate >='{BDate}' and FDocumentStatus='C'");

        if (list.Count == 0)
            throw Oops.Oh("金蝶无数据可同步！");
        
        //循环生产订单插入工单主表
        foreach (var item in list)
        {
            //配方编码
            string emid = item.FNumber;
            //产品编码
            string productId = item.FMaterialIdFNumber;
            if (item.FNumber.Split("V").Length > 0)
            {
                //拆分金蝶的配方版本号
                int engid = emid.Split("V")[1].Replace(".", "").ParseToInt();
                //判断配方是否存在
                if (!await producBomRespository.IsAnyAsync(x => x.EMID == emid || (x.Product_ID == productId && x.EngID == engid))
                    && !bomList.Any(x => x.EMID == emid || (x.Product_ID == productId && x.EngID == engid)))
                {
                    //配方主表字段赋值
                    ProductBOM obj = new()
                    {
                        EMID = emid,
                        EngID = emid.Split("V")[1].Replace(".", "").ParseToInt(),
                        Product_ID = item.FMaterialIdFNumber,
                        MakeDate = item.FCreateDate,
                        Poster = item.FCreatorId,
                        Manager = item.FApproverIdFNumber,
                        StandQty = 0,
                        Status=0,
                        FG_PartList = new List<ProductPartList>(),
                        _cid = cid,
                    };
                    //查询云星空物料清单中的材料明细数据
                    var childList = KingdeeUtil.Query<ENG_BOM_Child_Dto>(KingdeeFormConst.ENG_BOM, $"FNumber = '{emid}'");
                    
                    foreach (var childItem in childList)
                    {
                        //配方材料明细表字段赋值
                        ProductPartList child = new()
                        {
                            EMID = emid,
                            No = 1,
                            Product_ID = childItem.FMaterialIdFNumber,
                            Part_ID = childItem.FMaterialIdChildFNumber,
                            RountNo = childItem.FReplaceGroup,
                            Standard_Usage = childItem.FNUMERATOR,
                            Qty = childItem.FNUMERATOR.ParseToDecimal(),
                            MfgType = 0,
                            GtMType = 0,
                            _cid = cid
                        };
                        //防止配方材料重复插入
                        if (!obj.FG_PartList.Any(x => x.Part_ID == child.Part_ID
                        && x.No == child.No
                        && x.EMID == emid
                        && x.RountNo == child.RountNo
                        ))
                        {
                            //累计配方基数字段
                            obj.StandQty += child.Qty.ParseToDecimal();
                            obj.FG_PartList.Add(child);
                        }
                    }
                    bomList.Add(obj);
                }
            }
        }
        if (bomList.Count == 0)
        {
            throw Oops.Oh("当前同步的BOM本系统中已存在！");
        }

        try
        {
            producBomRespository.Context.Ado.BeginTran();
            
            await producBomRespository.Context.DeleteNav(bomList)
                .Include(x => x.FG_PartList)
                .ExecuteCommandAsync();
            var obj = await producBomRespository.AsInsertable(bomList)
                .AddSubList(x => x.FG_PartList)
                .ExecuteCommandAsync();
            producBomRespository.Context.Ado.CommitTran();
            return bomList;
        }
        catch (Exception ex)
        {
            producBomRespository.Context.Ado.RollbackTran();
            throw Oops.Oh(ex.Message);
        }
    }
    #endregion
}
